<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-input
          v-model="filterText"
          placeholder="输入用户名过滤"
        />
        <el-tree
          ref="tree"
          accordion
          node-key="id"
          :expand-on-click-node="false"
          :data="users"
          :props="defaultProps"
          :highlight-current="true"
          class="tree"
          default-expand-all
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        >
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="20" style="padding-left: 8px;">
        <div class="filter-div">
          <el-input
            v-model="listQuery.storeId"
            placeholder="店铺ID"
            style="width: 120px;"
            class="filter-item"
            @keyup.enter.native="getSettlement"
          />
          <el-input
            v-model="listQuery.storeName"
            placeholder="店铺名称"
            style="width: 120px;"
            class="filter-item"
            @keyup.enter.native="getSettlement"
          />
          <el-date-picker
            v-model="listQuery.date"
            style="width: 270px;"
            type="daterange"
            align="right"
            value-format="yyyy-MM-dd"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="getSettlement"
          />
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="getSettlement"
          >
            过滤
          </el-button>
        </div>
        <div class="tool-group">
          <el-row>
            <el-col :span="3">
              <el-button type="text" size="mini"> 用户：{{ currentUser.name }} </el-button>
            </el-col>
            <el-col :span="21">
              <el-button-group class="tool-btn">
                <el-button :loading="downloadLoading" size="mini" type="primary" @click="exportOneUser">导出当前</el-button>
                <el-button :loading="downloadLoading" size="mini" type="primary" @click="exportAll">导出所有</el-button>
                <el-button :loading="downloadLoading" size="mini" type="primary" @click="exportSelected">导出选中</el-button>
              </el-button-group>
            </el-col>
          </el-row>
        </div>
        <el-table
          v-loading="tableLoading"
          :data="settlements"
          size="mini"
          border
          height="500px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" min-width="6%" />
          <el-table-column align="center" min-width="12%" label="用户">
            <template slot-scope="{row}">
              <span>{{ row.user_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商店ID" align="center" min-width="12%">
            <template slot-scope="{row}">
              <span>{{ row.store_id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商店名" align="center" min-width="14%">
            <template slot-scope="{row}">
              <span>{{ row.store_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="预计跑分" align="center" min-width="8%">
            <template slot-scope="{row}">
              <span>{{ row.score/100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际跑分" align="center" min-width="8%">
            <template slot-scope="{row}">
              <span>{{ row.run_score/100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="利率" align="center" min-width="7%">
            <template slot-scope="{row}">
              <span>{{ row.rate + '%' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="利润" align="center" min-width="7%">
            <template slot-scope="{row}">
              <span>{{ row.value/10000 }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="开始时间" align="center" width="140px">
            <template slot-scope="{row}">
              <span>{{ row.start_time }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="结算日期" align="center" min-width="12%">
            <template slot-scope="{row}">
              <span>{{ row.stop_date }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { toTree, parseTime } from '@/utils'
import { fetchSettlement } from '@/api/settlement'
import { getAllUser } from '@/api/user'
import { Message } from 'element-ui'
const dateFormat = require('dateformat')

export default {
  name: 'Settlement',
  data() {
    return {
      downloadLoading: false,
      tableLoading: false,
      filterText: '',
      settlements: [],
      currentUser: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      users: [],
      rowSpan: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '最近三天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      multipleSelection: [],
      listQuery: {
        storeName: '',
        storeId: '',
        showDescendant: true,
        date: [
          dateFormat(new Date(), 'yyyy-mm-dd'),
          dateFormat(new Date(), 'yyyy-mm-dd')
        ]
      }
    }
  },
  computed: mapGetters({
    rootUserId: 'id'
  }),
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    getAllUser().then(response => {
      const list = response.data
      this.users = toTree(list)
      this.currentUser = this.users[0]
      this.$nextTick(() => this.$refs.tree.setCurrentKey(this.rootUserId))
      this.getSettlement()
    })
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleNodeClick(event, data) {
      this.currentUser = data.data
      this.getSettlement()
    },
    getSettlement() {
      const { storeName, storeId, showDescendant } = this.listQuery
      const startDate = this.listQuery.date[0]
      const endDate = this.listQuery.date[1]
      const query = { storeName, storeId, startDate, endDate, showDescendant }
      fetchSettlement(this.currentUser.id, query).then(response => {
        const list = response.data.list.map(item => {
          item.start_time = parseTime(item.start_time)
          item.stop_time = parseTime(item.stop_time)
          return item
        })
        list.sort((a, b) => {
          if (a.user_id > b.user_id) return 1
          if (a.user_id < b.user_id) return -1
          return a.store_id - b.store_id
        })
        if (list.length > 0) {
          // 计算需要合并的行
          const rowSpan = []
          let currentUserId = list[0].user_id
          let lastIndex = 0
          rowSpan[lastIndex] = 0
          for (let i = 0; i < list.length; i++) {
            if (currentUserId === list[i].user_id) {
              rowSpan[lastIndex] = rowSpan[lastIndex] + 1
              if (i > 0) rowSpan[i] = 0
            } else {
              lastIndex = i
              currentUserId = list[i].user_id
              rowSpan[i] = 1
            }
          }
          this.rowSpan = rowSpan
        }
        this.settlements = list
      })
    },
    showDescendant(v1) {
      this.listQuery.showDescendant = v1
      this.getSettlement()
    },
    export(data) {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户名', '店铺ID', '店铺名', '预计跑分', '实际跑分', '利率', '利润', '日期']
        const filterVal = ['user_name', 'store_id', 'store_name', 'score', 'run_score', 'rate', 'value', 'stop_date']
        const list = data.map(v => filterVal.map(j => {
          if (j === 'value') return v[j] ? v[j] / 100 : undefined
          if (j === 'rate') return v[j] ? `${v[j]}%` : undefined
          return v[j]
        }))
        excel.export_json_to_excel({
          header: tHeader,
          data: list,
          filename: '结算导出表',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    exportOneUser() {
      const user_id = this.currentUser.id
      const user_name = this.currentUser.name
      const list = this.settlements.filter(item => item.user_id === user_id)
        .map(v => {
          const result = {}
          Object.assign(result, v)
          return result
        })
      if (list.length === 0) {
        Message.warning('当前选中用户没有任何数据')
        return
      }
      this.genSumItem(user_name, list)
      this.export(list)
    },
    genSumItem(user_name, list) {
      const sum = { user_name, store_name: '所有店铺', store_id: '总计', score: '-', rate: '0', run_score: 0, value: 0 }
      list.forEach(item => {
        const { run_score, value } = item
        item.user_name = ''
        sum.run_score = sum.run_score + run_score
        sum.value = sum.value + value
      })
      list.unshift({}, sum)
    },
    exportAll() {
      if (this.settlements.length === 0) {
        Message.warning('未查询到数据')
        return
      }
      this.exportData(this.settlements)
    },
    exportSelected() {
      if (this.multipleSelection.length === 0) {
        Message.warning('未选择任何数据')
        return
      }
      this.exportData(this.multipleSelection)
    },
    exportData(dataList) {
      const setUserId = new Set()
      const map = {}
      dataList.forEach(item => {
        setUserId.add(item.user_id)
        const list = map[item.user_id] || []
        list.push(item)
        map[item.user_id] = list
      })
      let data = []
      setUserId.forEach(userId => {
        const list = map[userId].map(v => {
          const result = {}
          Object.assign(result, v)
          return result
        })
        this.genSumItem(list[0].user_name, list)
        data = data.concat(list)
      })
      this.export(data)
    }
  }
}
</script>

<style scoped>
  .tree {
      margin-top: 8px;
      /* background: #F0F9EB; */
    }
  .filter-div{
      padding-bottom: 8px;
  }
  .tool-group{
    padding-bottom: 4px;
  }
  .tool-btn {
    padding-left: 8px;
  }
</style>
